package org.dftproject.genesis.ui.pages.pedigree.tree;

import java.util.List;

import org.eclipse.draw2d.AbstractLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;

public class FixedWidthColumnLayout extends AbstractLayout {

	private int spacing;
	private int width;

	public FixedWidthColumnLayout() {
		this.spacing = 0;
		this.width = 0;
	}
	
	public FixedWidthColumnLayout(int width, int spacing) {
		this.spacing = spacing;
		this.width = width;
	}
	
	public int getSpacing() {
		return spacing;
	}

	public void setSpacing(int spacing) {
		this.spacing = spacing;
	}
	
	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	@Override
	protected Dimension calculatePreferredSize(IFigure container, int wHint, int hHint) {
		@SuppressWarnings("unchecked")
		List<IFigure> children = container.getChildren();
		
		int height = Math.max(0, children.size() - 1) * spacing;
		
		for (IFigure child : children) {
			Dimension childSize = child.getPreferredSize(width, -1);
			height += childSize.height;
		}
		
		Insets insets = container.getInsets();
		return new Dimension(width, height).expand(insets.getWidth(), insets.getHeight()).union(getBorderPreferredSize(container));
	}

	public void layout(IFigure container) {
		@SuppressWarnings("unchecked")
		List<IFigure> children = container.getChildren();
		
		Rectangle clientArea = container.getClientArea();
		int x = clientArea.x;
		int y = clientArea.y;
		
		for (IFigure child : children) {
			Dimension childSize = child.getPreferredSize(width, -1);
			Rectangle bounds = new Rectangle(x, y, width, childSize.height);
			y += childSize.height + spacing;
			child.setBounds(bounds);
		}
	}

}
